<?php
class System_Url
{
    private $_baseUrl = null;
    private $_rewriteUrls = false;

    public function __construct($baseUrl, $rewriteUrls = false)
    {
        $this->_baseUrl = $baseUrl;
        $this->_rewriteUrls = $rewriteUrls;
    }

    public function getBaseUrl()
    {
        return $this->_baseUrl;
    }

    // page?title=xxx  ->
    public function parse($str)
    {
        if(empty($str)) {
            return '';
        }
        $pos = strpos($str, '?');
        if ($pos === false) {
            return $this->url($str);
        } else {
            $router = substr($str, 0, $pos);
            $urlParams = explode('&', substr($str, ($pos + 1)));
            $params = array();
            foreach($urlParams as $url) {
                list($k, $v) = explode('=', $url);
                $params[$k] = $v;
            }
            return $this->url($router, $params);
        }
    }

    public function href($router = null, $query = array())
    {
        $link = $this->getBaseUrl();
        if($router) {
            if($router == 'index') {
                $router = '';
            } else {
                $router = trim($router, '/');
            }
            if($this->_rewriteUrls) {
                $link .= '/' . $router;
            } else {
                $link .= '/?router=' . $router;
            }
        }

        if($query) {
            if($this->_rewriteUrls) $sep = '?'; else $sep = '&';
            foreach ($query as $key => $value) {
                if ($value) {
                    $link .= $sep . $key . '=' . urlencode($value);
                    $sep = '&';
                }
            }
        }
        return $link;
    }

    public function url($router = null, $query = array())
    {
        $link = $this->getBaseUrl();
        if($router) {
            if($this->_rewriteUrls) {
                $link .= '/' . trim($router, '/');
            } else {
                $link .= '/?router=' . trim($router, '/');
            }
        }

        if($query) {
            if($this->_rewriteUrls) $sep = '?'; else $sep = '&';
            foreach ($query as $key => $value) {
                if ($value) {
                    $link .= $sep . $key . '=' . urlencode($value);
                    $sep = '&';
                }
            }
        }

        return $link;
    }
}
